package com.mobilesales.android.c2dm.parsers;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.mobilesales.android.R;
import com.mobilesales.android.activities.employees.MessageRead;
import com.mobilesales.android.database.EmployeeManager;
import com.mobilesales.android.model.employees.Employee;
import com.mobilesales.android.model.employees.Message;
import com.mobilesales.android.services.EmployeeServiceClient;
import com.mobilesales.android.util.Constants;
import com.mobilesales.android.util.Settings;

public class EmployeeMessageParser extends MessageParserBase {

	
	private EmployeeManager manager;
	private EmployeeServiceClient service;

	public EmployeeMessageParser(Context context) {
		super(context);
	}
	
	public EmployeeMessageParser() {
		super();
	}	
	
	@Override
	public boolean parseMessage(String method, String arg) {
		manager = new EmployeeManager(getContext());
		service = new EmployeeServiceClient(Settings.EmployeeService());
		try {
			this.invokeMethod(EmployeeMessageParser.class, method,arg);
			return true;
		}
		catch(Exception ex) {
			Log.e("MessageParser", ex.getMessage(), ex);
			return false;
		}
		finally {
			manager.Close();
		}
	}
	
	public void GetEmployee(Integer id) throws Exception {
		Employee employee = service.GetEmployee(id);
		if (employee!=null) {
			if (!manager.StoreEmployee(employee))
				throw new Exception("Could not store employee");
		}
		else {
			throw new Exception("Retrieved employee is null");
		}		
	}
	
	public void DeleteEmployee(Integer id) throws Exception {
		if (!manager.RemoveEmployee(id))
			throw new Exception("Could not delete employee");
	}
	
	public void GetMessage(Integer id) throws Exception {
		Message msg = service.GetMessage(id);
		if (msg!=null) {
			if (!manager.StoreMessage(msg))
				throw new Exception("Could not store message");
			else {
				Context ctx = this.getContext();
				Intent intent = new Intent(ctx, MessageRead.class);
				intent.putExtra(Constants.MessageId, msg.Id);
				String title = ctx.getString(R.string.NewMessageReceived);
				this.createNotification(title, msg.Subject, intent);
			}
		}
		else {
			throw new Exception("Retrieved message is null");
		}				
	}
	
	public void DeleteMessage(Integer id) throws Exception {
		if (!manager.RemoveMessage(id))
			throw new Exception("Could not delete message");
	}	
	
}
